from datetime import datetime
import json
from sqlalchemy import text
from sqlalchemy.exc import PendingRollbackError

# from kpi.Kpi_service import str2Array




    

def get2DateDays(date_str1,date_str2):
    # 将字符串转换为datetime对象
    date1 = datetime.strptime(date_str1, "%Y-%m-%d")
    date2 = datetime.strptime(date_str2, "%Y-%m-%d")
    # 计算两个日期之间的天数差
    days_difference = (date2 - date1).days
    return days_difference


def kpi(request,session):

    from kpi.Kpi_service import str2Array

    result = {
        "code": 200,
        "message": "trigger",
        "data": {
            "total_vehicles": "",
            "mileages": {  # 智驾里程
                "total_mileage": "",  # 总里程数 包含智驾和非智驾
                "total_intelligent_driving_mileage": "",  # 智驾总里程数
                "total_intelligent_driving_mileage_change_rate": "",  # 智驾总里程数增减百分比, 正数为增加，负数为减少
                "detail_intelligent_driving": {
                    "acc": "",  # 自适应巡航
                    "ica": "",  # 智能巡航
                    "hnop": "",  # 高速智驾
                    "unop": "",  # 低速智驾
                    "ldp": "",   # 车道偏离预防
                    "elk": "",   # 车道偏离预防
                    "safe": ""   # 车道偏离预防
                }
            },
            "preference": {  # 智驾偏好
                "apa_times_rate_rate": "",  # apa激活次数占比
                "apa_activate_vehicle": "",  # apa激活车数量
                "apa_activate_vehicle_change": "",  # apa激活车辆与上一周期对比变化数量，正数为增加，负数为减少
                "rpa_times_rate_rate": "",  # rpa激活次数占比
                "rpa_activate_vehicle": "",  # rpa激活车数量
                "rpa_activate_vehicle_change": "",  # rpa激活车辆与上一周期对比变化数量，正数为增加，负数为减少
                "vpa_times_rate_rate": "",  # vpa激活次数占比(暂时没有值)
                "vpa_activate_vehicle": "",  # vpa激活车数量(暂时没有值)
                "vpa_activate_vehicle_change": "",  # vpa激活车辆与上一周期对比变化数量，正数为增加，负数为减少(暂时没有值)
            },
            "total_intelligent_driving_vehicles": "",  # 智驾激活车辆总数，包含所有智驾类型
            "total_intelligent_driving_times": "",  # 智驾激活总次数，包含所有智驾类型
            "total_intelligent_driving_vehicles_change": "",  # 智驾激活车辆总数，包含所有智驾类型
            "total_intelligent_driving_times_change": "",  # 智驾激活总次数，包含所有智驾类型
            "total_parking_intelligent_vehicles": "",  # 自动泊车激活车辆数
            "total_parking_intelligent_vehicles_change": "",  # 自动泊车激活车辆数与上一周期对比，正数为增加，负数为减少
            "day_times_parking_intelligent": "",  # 自动泊车单车日均激活次数，
            "day_times_parking_intelligent_day_times_change": "",  # 自动泊车单车日均激活次数与上一周期对比，正数为增加，负数为减少
            "apa_duration_parking_duration": "",  # apa_单次泊车平均时长 秒
            "apa_duration_parking_duration_change": "",  # apa_单次泊车平均时长与上一周期对比， 秒，正数为增加，负数为减少
            "rpa_duration_parking_duration": "",  # rpa_单次泊车平均时长 秒
            "rpa_duration_parking_duration_change": "",  # rpa_单次泊车平均时长与上一周期对比， 秒，正数为增加，负数为减少
            "vpa_duration_parking_duration": "",  # vpa_单次泊车平均时长 秒
            "vpa_duration_parking_duration_change": "",  # vpa_单次泊车平均时长与上一周期对比， 秒，正数为增加，负数为减少
            # 行车功能指标  表数据
            "driving_function_indicators_data": [
                {
                    "function": "",  # 功能名称
                    "vehicles": "",  # 激活车辆数
                    "activate": "",  # 激活次数
                    "avg_mileage": "",  # 单次平均里程
                    "activate_rate": []
                }
            ],
            # 泊车功能指标
            "parking_function_indicators_data": [
                {
                    "function": "",  # 功能名称（VPA，APA，RPA）
                    "avg_duration": "",  # 单次泊车平均时长
                    "activate": "",  # 激活次数
                    "success_rate": "",  # 成功率
                }
            ]
        }
    }
    start_time = request.json["start_time"]
    end_time = request.json["end_time"]
    start_time_pre = request.json["start_time_pre"]
    end_time_pre = request.json["end_time_pre"]

    days = get2DateDays(start_time, end_time) + 1
    days_pre = get2DateDays(start_time_pre, end_time_pre) + 1
    
    carcode = str2Array(request.json["car_code"])    
    otas = str2Array(request.json["ota_versions"])


    carcodesStr = ""
    carcodesStr2 = ""
    carcodesStrArray = []
    for code in carcode:
        if len(code) > 0:
            carcodesStrArray.append(code)
    if len(carcodesStrArray) > 0:
        carcodesStr = f" and SUBSTRING_INDEX(md, '-', 1) in  ('{"','".join(carcodesStrArray)}')"
        carcodesStr2 = f" and int_model_code in  ('{"','".join(carcodesStrArray)}')"   

         

    otasStr = ""
    otasStr2 = ""
    otasStrArray = []
    for ota in otas:
        if len(ota) > 0:
            otasStrArray.append(ota)
    if len(otasStrArray) > 0:
        otasStr = f" and left(SUBSTRING_INDEX(vs, '_',-1),length(SUBSTRING_INDEX(vs, '_',-1))-3) in ('{"','".join(otasStrArray)}')"
        otasStr2 = f" and ota_ver_stamp in ('{"','".join(otasStrArray)}')"



    try:
        # with table_17 as (
        #         select
        # CONVERT(REPLACE(ekt.Total_odo, '"', ''), FLOAT4) as Total_odo, DATE_FORMAT(FROM_UNIXTIME(ekt.ts / 1000), '%Y-%m-%d') as data_temp
        # from explor_kpi_tid_100017 ekt
        # )
        # select
        # IFNULL(round(sum(t17.Total_odo), 2), 0) as sum_total_odo
        # from table_17 t17
        # where
        # t17.data_temp >= '{start_time}' and t17.data_temp <= '{end_time}'
        # 总里程数
        sql1 = f"""
                select ifnull(sum(max_total)-sum(min_total),0) as total
                from (select vin_id
                            ,max(max_total) as max_total
                            ,min(min_total) as min_total
                        from (select vin_id
                                    ,max_total
                                    ,min_total
                                from all_miles_info_result
                                where date_ts >= '{start_time}'
                                and date_ts <= '{end_time}'
                                    {carcodesStr2} {otasStr2} 
                            ) t
                        group by vin_id
                    ) t
                """
        # 智驾总里程数和同比
        sql2 = f"""
         select t.sum_odo
		       ,ifnull(t1.sum_odo_pre,0)
			   ,ifnull(t.acc_sum_odo,0)
			   ,ifnull(t.tja_ica_sum_odo,0)
			   ,ifnull(t.h_nop_sum_odo,0)
			   ,ifnull(t.u_nop_sum_odo,0)
			   ,ifnull(t.ldp_sum_odo,0)
			   ,ifnull(t.elk_sum_odo,0)
			   ,ifnull(t.safety_stop_sum_odo,0)
		  from (select sum(sum_odo) as sum_odo
				       ,sum(case when tid = 'ACC' then sum_odo else null end) as acc_sum_odo
					   ,sum(case when tid = 'TJA/ICA' then sum_odo else null end) as tja_ica_sum_odo
					   ,sum(case when tid = 'LDP' then sum_odo else null end) as ldp_sum_odo
					   ,sum(case when tid = 'H-NOP' then sum_odo else null end) as h_nop_sum_odo
					   ,sum(case when tid = 'U-NOP' then sum_odo else null end) as u_nop_sum_odo
					   ,sum(case when tid = 'ELK' then sum_odo else null end) as elk_sum_odo
					   ,sum(case when tid = 'Safety Stop' then sum_odo else null end) as safety_stop_sum_odo
				  from auto_driving_miles_time_result
				 where date_ts >= '{start_time}'
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
               ) t
          left join 
		       (select sum(sum_odo) as sum_odo_pre
				  from auto_driving_miles_time_result
				 where date_ts >= '{start_time_pre}'
				   and date_ts <= '{end_time_pre}'
					   {carcodesStr2} {otasStr2} 
			   ) t1 
			on 1=1
                """
        # 车辆总数
        sql3 = f"""
				select count(distinct vin_id) as nums
				  from (select vin_id
				               ,date_ts
							   ,ota_ver_stamp
							   ,int_model_code
						  from auto_driving_miles_time_result
						 union all 
						select vin_id
				               ,date_ts
							   ,ota_ver_stamp
							   ,int_model_code
						  from auto_parking_overview_result
						 union all 
						select vin_id
				               ,date_ts
							   ,ota_ver_stamp
							   ,int_model_code
						  from all_miles_info_result  
					   ) t
				 where date_ts >= '{start_time}'
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
                """
        # APA激活车辆 触发100009埋点就代表APA激活   /  RPA（100050）激活车辆： 车辆触发100050埋点就代表RPA激活。
        sql4 = f"""
		select t.apa_num
			   ,t.rpa_num
			   ,t.vpa_num
			   ,t1.apa_pre_num
			   ,t1.rpa_pre_num
			   ,t1.vpa_pre_num
		  from (select ifnull( count(distinct case when tid = 'APA' then vin_id else null end),0) as apa_num
					   ,ifnull(count(distinct case when tid = 'RPA' then vin_id else null end),0) as rpa_num
					   ,ifnull(count(distinct case when tid = 'VPA' then vin_id else null end),0) as vpa_num
				  from auto_parking_function_result
				 where date_ts >= '{start_time}' 
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
			   ) t
		  left join 
			   (select ifnull( count(distinct case when tid = 'APA' then vin_id else null end),0) as apa_pre_num
					   ,ifnull(count(distinct case when tid = 'RPA' then vin_id else null end),0) as rpa_pre_num
					   ,ifnull(count(distinct case when tid = 'VPA' then vin_id else null end),0) as vpa_pre_num
				  from auto_parking_function_result
				 where date_ts >= '{start_time_pre}' 
				   and date_ts <= '{end_time_pre}'
					   {carcodesStr2} {otasStr2} 
			   ) t1
			on 1=1 ;
                """
        # 智驾激活车辆和次数
        sql5 = f"""
        select t.sum_ct
		       ,t.vid_ct
			   ,t1.sum_ct_pre
			   ,t1.vid_ct_pre
		  from (select count(distinct vin_id) as vid_ct
					   ,ifnull(sum(ct),0) as sum_ct
				  from auto_driving_miles_time_result
				 where date_ts >= '{start_time}'
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
               ) t
          left join 
		       (select count(distinct vin_id) as vid_ct_pre
					   ,ifnull(sum(ct),0) as sum_ct_pre
				  from auto_driving_miles_time_result
				 where date_ts >= '{start_time_pre}'
				   and date_ts <= '{end_time_pre}'
					   {carcodesStr2} {otasStr2} 	   
			   ) t1
            on 1=1  ;
                """
        # 自动泊车单车日均激活次数
        sql6 = f"""
       select t1.counts
		       ,t.apa_dur
			   ,t.apa_times
			   ,ifnull(round(t.apa_times/t1.apa_total_count*100,0),0) as suc_rate_apa
			   ,t.rpa_dur
			   ,t.rpa_times
			   ,ifnull(round(t.rpa_times/t1.rpa_total_count*100,0),0) as suc_rate_rpa
			   ,t.vpa_dur
			   ,t.vpa_times
			   ,ifnull(round(t.vpa_times/t1.vpa_total_count*100,0),0) as suc_rate_vpa
			   ,ifnull(t1.apa_total_count,0) as apa_total_count
			   ,ifnull(t1.rpa_total_count,0) as apa_total_count
			   ,ifnull(t1.vpa_total_count,0) as apa_total_count
		  from (select ifnull(round(sum(case when tid = 'APA' then pk_dur else 0 end )
		                /sum(case when tid = 'APA' then sucs_ct else 0 end)/1000,0),0) as apa_dur
					   ,ifnull(sum(case when tid = 'APA' then sucs_ct else 0 end ),0)  as apa_times
					   ,ifnull(round(sum(case when tid = 'RPA' then pk_dur else 0 end )
		                /sum(case when tid = 'RPA' then sucs_ct else 0 end)/1000,0),0) as rpa_dur
					   ,ifnull(sum(case when tid = 'RPA' then sucs_ct else 0 end ),0)  as rpa_times
					   ,ifnull(round(sum(case when tid = 'VPA' then pk_dur else 0 end )
		                /sum(case when tid = 'VPA' then sucs_ct else 0 end)/1000,0),0) as vpa_dur
					   ,ifnull(sum(case when tid = 'VPA' then sucs_ct else 0 end ),0)  as vpa_times
				  from auto_parking_function_result
				 where date_ts >= '{start_time}' 
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
			   ) t
		  left join 
               (select ifnull(sum(case when tid = 'APA' then auto_parking_ct else 0 end ),0) as apa_total_count
			           ,ifnull(sum(case when tid = 'RPA' then auto_parking_ct else 0 end ),0) as rpa_total_count
					   ,ifnull(sum(case when tid = 'VPA' then auto_parking_ct else 0 end ),0) as vpa_total_count
					   ,count(distinct vin_id) as counts
				  from auto_parking_function_result
				 where date_ts >= '{start_time}' 
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
			   ) t1 
			on 1=1;
                """
        # print(sql6)

        sql6_pre = f"""
       select t1.counts
		       ,t.apa_dur
			   ,t.apa_times
			   ,ifnull(round(t.apa_times/t1.apa_total_count*100,0),0) as suc_rate_apa
			   ,t.rpa_dur
			   ,t.rpa_times
			   ,ifnull(round(t.rpa_times/t1.rpa_total_count*100,0),0) as suc_rate_rpa
			   ,t.vpa_dur
			   ,t.vpa_times
			   ,ifnull(round(t.vpa_times/t1.vpa_total_count*100,0),0) as suc_rate_vpa
			   ,ifnull(t1.apa_total_count,0) as apa_total_count
			   ,ifnull(t1.rpa_total_count,0) as apa_total_count
			   ,ifnull(t1.vpa_total_count,0) as apa_total_count
		  from (select ifnull(round(sum(case when tid = 'APA' then pk_dur else 0 end )
		                /sum(case when tid = 'APA' then sucs_ct else 0 end)/1000,0),0) as apa_dur
					   ,ifnull(sum(case when tid = 'APA' then sucs_ct else 0 end ),0)  as apa_times
					   ,ifnull(round(sum(case when tid = 'RPA' then pk_dur else 0 end )
		                /sum(case when tid = 'RPA' then sucs_ct else 0 end)/1000,0),0) as rpa_dur
					   ,ifnull(sum(case when tid = 'RPA' then sucs_ct else 0 end ),0)  as rpa_times
					   ,ifnull(round(sum(case when tid = 'VPA' then pk_dur else 0 end )
		                /sum(case when tid = 'VPA' then sucs_ct else 0 end)/1000,0),0) as vpa_dur
					   ,ifnull(sum(case when tid = 'VPA' then sucs_ct else 0 end ),0)  as vpa_times
				  from auto_parking_function_result
				 where date_ts >= '{start_time_pre}' 
				   and date_ts <= '{end_time_pre}'
					   {carcodesStr2} {otasStr2} 
			   ) t
		  left join 
               (select sum(case when tid = 'APA' then auto_parking_ct else 0 end ) as apa_total_count
			           ,sum(case when tid = 'RPA' then auto_parking_ct else 0 end ) as rpa_total_count
					   ,sum(case when tid = 'VPA' then auto_parking_ct else 0 end ) as vpa_total_count
					   ,count(distinct vin_id) as counts
				  from auto_parking_function_result
				 where date_ts >= '{start_time_pre}' 
				   and date_ts <= '{end_time_pre}'
					   {carcodesStr2} {otasStr2} 
			   ) t1 
			on 1=1;
                        """
        sql7 = f"""
        select acc_ct
		       ,tja_ica_ct
			   ,h_nop_ct
			   ,u_nop_ct
			   ,acc_vin
			   ,tja_ica_vin
			   ,h_nop_vin
			   ,u_nop_vin
			   ,0 as acc_len_avg
			   ,0 as tja_ica_len_avg
			   ,0 as h_nop_len_avg
			   ,0 as u_nop_len_avg
			   ,0 as acc_rate
			   ,0 as tja_ica_rate
			   ,0 as h_nop_rate
			   ,0 as u_nop_rate
		  from (select ifnull(count(distinct case when tid = 'ACC' then vin_id else null end),0) as acc_vin
					   ,ifnull(count(distinct case when tid = 'TJA/ICA' then vin_id else null end),0) as tja_ica_vin
					   ,ifnull(count(distinct case when tid = 'H-NOP' then vin_id else null end),0) as h_nop_vin
					   ,ifnull(count(distinct case when tid = 'U-NOP' then vin_id else null end),0) as u_nop_vin
					   ,ifnull(sum(case when tid = 'ACC' then ct else 0 end),0) as acc_ct
					   ,ifnull(sum(case when tid = 'TJA/ICA' then ct else 0 end),0) as tja_ica_ct
					   ,ifnull(sum(case when tid = 'H-NOP' then ct else 0 end),0) as h_nop_ct
					   ,ifnull(sum(case when tid = 'U-NOP' then ct else 0 end),0) as u_nop_ct
				  from auto_driving_miles_time_result
				 where date_ts >= '{start_time}'
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
               ) t   ;
                """
        sql8 = f"""
         select t.vin_avg,t1.vin_avg_pre
		  from (select ifnull(round(sum(auto_parking_ct)/{days}/count(distinct vin_id),4),0) as vin_avg
				  from auto_parking_function_result
				 where date_ts >= '{start_time}' 
				   and date_ts <= '{end_time}'
					   {carcodesStr2} {otasStr2} 
               ) t
          left join 
		       (select ifnull(round(sum(auto_parking_ct)/{days_pre}/count(distinct vin_id),4),0) as vin_avg_pre
				  from auto_parking_function_result
				 where date_ts >= '{start_time_pre}' 
				   and date_ts <= '{end_time_pre}'
					   {carcodesStr2} {otasStr2} 
			   ) t1 
            on 1=1 ;
                """
        result_data_1 = session.execute(text(sql1)).all()
        result_data_2 = session.execute(text(sql2)).all()
        result_data_3 = session.execute(text(sql3)).all()
        result_data_4 = session.execute(text(sql4)).all()
        result_data_5 = session.execute(text(sql5)).all()
        result_data_6 = session.execute(text(sql6)).all()
        result_data_6_pre = session.execute(text(sql6_pre)).all()
        result_data_7 = session.execute(text(sql7)).all()
        result_data_8 = session.execute(text(sql8)).all()
        print('result_data_1',result_data_1)
        print('result_data_2',result_data_2)
        print('result_data_3',result_data_3)
        print('result_data_4',result_data_4)
        print('result_data_5',result_data_5)
        print('result_data_6',result_data_6)
        print('result_data_6_pre',result_data_6_pre)
        print('result_data_7',result_data_7)
        print('result_data_8',result_data_8)
        result["data"]["total_vehicles"] = result_data_3[0][0]
        result["data"]["mileages"]["total_mileage"] = float(format(result_data_1[0][0], '.2f'))
        result["data"]["mileages"]["total_intelligent_driving_mileage"] = float(format(result_data_2[0][0], '.2f'))
        result["data"]["mileages"]["total_intelligent_driving_mileage_change_rate"] = float(format(result_data_2[0][1], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["acc"] = float(format(result_data_2[0][2], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["ica"] = float(format(result_data_2[0][3], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["hnop"] = float(format(result_data_2[0][4], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["unop"] = float(format(result_data_2[0][5], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["ldp"] = float(format(result_data_2[0][6], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["elk"] = float(format(result_data_2[0][7], '.2f'))
        result["data"]["mileages"]["detail_intelligent_driving"]["safeStop"] = float(format(result_data_2[0][8], '.2f'))

        result["data"]["preference"]["apa_times_rate_rate"] = 0
        result["data"]["preference"]["apa_activate_vehicle"] = float(format(result_data_4[0][0], '.2f'))
        result["data"]["preference"]["apa_activate_vehicle_change"] = float(format((result_data_4[0][0] - result_data_4[0][1]), '.2f'))
        result["data"]["preference"]["rpa_times_rate_rate"] = 0
        result["data"]["preference"]["rpa_activate_vehicle"] = float(format(result_data_4[0][2], '.2f'))
        result["data"]["preference"]["rpa_activate_vehicle_change"] = float(format((result_data_4[0][2] - result_data_4[0][3]), '.2f'))
        result["data"]["preference"]["vpa_times_rate_rate"] = 0
        result["data"]["preference"]["vpa_activate_vehicle"] = float(format(result_data_4[0][4], '.2f'))
        result["data"]["preference"]["vpa_activate_vehicle_change"] = float(format((result_data_4[0][4] - result_data_4[0][5]), '.2f'))

        result["data"]["total_intelligent_driving_vehicles"] = result_data_5[0][1]
        result["data"]["total_intelligent_driving_times"] = float(format(result_data_5[0][0], '.0f'))
        result["data"]["total_intelligent_driving_vehicles_change"] = result_data_5[0][1] - result_data_5[0][3]
        # times_ai = result_data_5[0][0]
        # times_ai_pre = result_data_5[0][2]
        # rate_times_change = float(format((times_ai - times_ai_pre) / (times_ai_pre if times_ai_pre > 0 else 1) * 100,
        #                                  '.0f'))

        print('在这里：')
        print(result_data_5[0][2])

        result["data"]["total_intelligent_driving_times_change"] =  int(result_data_5[0][2])

        result["data"]["total_parking_intelligent_vehicles"] = int(result_data_6[0][0])
        result["data"]["total_parking_intelligent_vehicles_change"] = int(result_data_6[0][0] - result_data_6_pre[0][0])
        # result["data"]["day_times_parking_intelligent"] = result_data_6[0][0]

        # times_parking = result_data_6[0][2]
        # times_vehicles = result_data_6[0][0]
        # times_parking_pre = result_data_6_pre[0][2]
        # times_vehicles_pre = result_data_6_pre[0][0]
        # days = get2DateDays(start_time, end_time) + 1
        # every_vehicle_day = times_parking / days / (times_vehicles if times_vehicles > 0 else 1)
        # every_vehicle_day_pre = times_parking_pre / days / (times_vehicles_pre if times_vehicles_pre > 0 else 1)
        # rate_parking_change = float(format((every_vehicle_day - every_vehicle_day_pre) /
        #                                    (every_vehicle_day_pre if every_vehicle_day_pre > 0 else 1) * 100, '.0f'))
        # rate_parking_change = float(format((times_parking - times_parking_pre) /
        #                              (times_parking_pre if times_parking_pre > 0 else 1) * 100, '.0f'))
        result["data"]["day_times_parking_intelligent"] = float(result_data_8[0][0])
        result["data"]["day_times_parking_intelligent_day_times_change"] = float(result_data_8[0][1])
        result["data"]["apa_duration_parking_duration"] = int(result_data_6[0][1])
        result["data"]["apa_duration_parking_duration_change"] = float(format(
            (result_data_6[0][1] - result_data_6_pre[0][1]),
            '.0f'))
        result["data"]["rpa_duration_parking_duration"] = int(result_data_6[0][4])
        result["data"]["rpa_duration_parking_duration_change"] = float(format(
            (result_data_6[0][4] - result_data_6_pre[0][4]),
            '.0f'))
        result["data"]["vpa_duration_parking_duration"] = int(result_data_6[0][7])
        result["data"]["vpa_duration_parking_duration_change"] = float(format(
            (result_data_6[0][7] - result_data_6_pre[0][7]),
            '.0f'))

        result["data"]["driving_function_indicators_data"] = [
            {
                "function": "ACC", "vehicles": result_data_7[0][4], "activate": float(result_data_7[0][0]),
                "avg_mileage": float(format(result_data_7[0][8], '.3f')), "activate_rate": result_data_7[0][12]
            }, {
                "function": "TJA/ICA", "vehicles": result_data_7[0][5], "activate": float(result_data_7[0][1]),
                "avg_mileage": float(format(result_data_7[0][9], '.3f')), "activate_rate": result_data_7[0][13]
            }, {
                "function": "HNOP", "vehicles": result_data_7[0][6], "activate": float(result_data_7[0][2]),
                "avg_mileage": float(format(result_data_7[0][10], '.3f')), "activate_rate": result_data_7[0][14]
            }, {
                "function": "UNOP", "vehicles": result_data_7[0][7], "activate": float(result_data_7[0][3]),
                "avg_mileage": float(format(result_data_7[0][11], '.3f')), "activate_rate": result_data_7[0][15]
            }
        ]
        result["data"]["parking_function_indicators_data"] = [
            {
                "function": "APA",
                "avg_duration": float(result_data_6[0][1]),
                "activate": float(result_data_6[0][10]),
                "success_rate": float(result_data_6[0][3]),
            },
            {
                "function": "RPA",
                "avg_duration": float(result_data_6[0][4]),
                "activate": float(result_data_6[0][11]),
                "success_rate": float(result_data_6[0][6]),
            },
            {
                "function": "VPA",
                "avg_duration": float(result_data_6[0][7]),
                "activate": float(result_data_6[0][12]),
                "success_rate": float(result_data_6[0][9]),
            }
        ]
        # result["data"]["parking_function_indicators_data_list"] = [
        #     [
        #         int(format(result_data_8[0][1], '0.0f')),
        #         int(result_data_8[0][0]),
        #         int(format(result_data_8[0][2], '0.0f')),
        #     ],
        #     [
        #         int(format(result_data_8[0][4], '0.0f')),
        #         int(result_data_8[0][3]),
        #         int(format(result_data_8[0][5], '0.0f')),
        #     ],
        #     [
        #         int(format(result_data_8[0][7], '0.0f')),
        #         int(result_data_8[0][6]),
        #         int(format(result_data_8[0][8], '0.0f')),
        #     ]
        # ]
        session.commit()
        session.remove()
    except PendingRollbackError:
        session.commit()
        session.remove()
    except Exception as e:
        print(e)
    return json.dumps(result, ensure_ascii=False)